<?php

declare(strict_types=1);
/**
 * 小程序问题反馈API
 * User：Abell
 * Date：2020/5/25
 */

namespace App\Service;
use App\Constants\ErrorCode;
use App\Dao\{WxserviceOpeDao,WxserviceTypeDao,WxserviceDao,AdminLogDao};
use App\Exception\BusinessException;
use App\Utils\{StringUtil,ServerUtil};
use Hyperf\Utils\Context;
use Hyperf\Utils\Str; // 日志记录

class WxserviceService
{

    private $jwt;
    public function __construct()
    {
        $this->jwt = Context::get('jwt_token');
    }

    /**
     * 后台编辑更新单个问题反馈信息
     * @Author abell
     * @DateTime 2020-05-28
     * @param array $request
     * @return array
     */
    public function editForm($request){
        try {
            $before_data = make(WxserviceDao::class)->getForm($request['id']);
            $update_data = ['update_time'=>time()];
            if(array_key_exists('statue',$request)) $update_data['statue'] = $request['statue'];
            if(array_key_exists('reply',$request)) $update_data['reply'] = $request['reply'];
            $update_edit = make(WxserviceDao::class)->editForm($update_data,$request['id']);
            if($update_edit){
                make(AdminLogDao::class)->addLog('问题反馈处理，处理前数据“'.json_encode(['id'=>$request['id'],'data'=>$before_data]).'”'.'处理后数据“'.json_encode($update_data).'”');
                return ['code'=>ErrorCode::SUCCESS,'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),'data'=>$update_edit];
            }else{
                return ['code'=>ErrorCode::ERR_BUESSUS,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_BUESSUS),'data'=>$update_edit];
            }
        }catch (\Exception $e) {
            ServerUtil::info('基本的表单提交客服信息列表查看和编辑/admin/wxservice/edit', ['error' => $e->getMessage(), 'request' => $request], 'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }

    /**
     * 后台获取单个问题反馈信息
     * @Author abell
     * @DateTime 2020-05-28
     * @param array $request
     * @return array
     */
    public function getForm($request){
        try {
            $has_form = make(WxserviceDao::class)->getForm($request['id']);
            if($has_form){
                return ['code'=>ErrorCode::SUCCESS,'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),'data'=>$has_form];
            }else{
                return ['code'=>ErrorCode::ERR_BUESSUS,'msg'=>'数据不存在','data'=>$has_form];
            }
        }catch (\Exception $e) {
            ServerUtil::info('基本的表单提交客服信息列表查看和编辑/admin/wxservice/edit', ['error' => $e->getMessage(), 'request' => $request], 'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }

    /**
     * 基本的表单提交客服信息列表查看 问题反馈列表
     * @Author abell
     * @DateTime 2020-05-28
     * @param array $request
     * @return array
     */
    public function formList($request){
        try {
            $pageSize = array_key_exists('pageSize',$request) ? $request['pageSize'] : 15;
            $pageNum = array_key_exists('page',$request) ? (int)$request['page'] : 1;
            $where = [];
            if(array_key_exists('mobile',$request)) $where['mobile'] = $request['mobile'];
            if(array_key_exists('type_id',$request)) $where['type_id'] = $request['type_id'];
            if(array_key_exists('statue',$request)) $where['statue'] = $request['statue'];
            if(array_key_exists('start_time',$request)){
                $start_time = $request['start_time'];
                if(array_key_exists('end_time',$request)) $end_time = $request['end_time'];
                $result = make(WxserviceDao::class)->formListNum($where,$pageSize,$pageNum,'add_time',$start_time,$end_time);
            }else{
                $result = make(WxserviceDao::class)->formListNum($where,$pageSize,$pageNum);
            }
            // 处理列表数据 运营商 问题分类 问题类型
            $type_ids = array_column($result['data'],'type_id');
            $operator_ids = array_column($result['data'],'operator_id');
            $wxservice_ope_ids = array_column($result['data'],'wxservice_ope_id');

            $type_names = make(WxserviceTypeDao::class)->getListByIds($type_ids,['id','title']);
            $operator_names = make(WxserviceOpeDao::class)->getListByIds($operator_ids,['id','title']);
            $wxservice_ope_names = make(WxserviceOpeDao::class)->getListByIds($wxservice_ope_ids,['id','title']);

            $type_names_dic = make(StringUtil::class)->customArrayByKeyValue($type_names,'id','title');
            $operator_names_dic = make(StringUtil::class)->customArrayByKeyValue($operator_names,'id','title');
            $wxservice_ope_names_dic = make(StringUtil::class)->customArrayByKeyValue($wxservice_ope_names,'id','title');

            foreach ($result['data'] as &$datum){
                if(array_key_exists($datum['type_id'],$type_names_dic)) {
                    $datum['type_name'] = $type_names_dic[$datum['type_id']];
                }
                if(array_key_exists($datum['operator_id'],$operator_names_dic)) {
                    $datum['operator_name'] = $operator_names_dic[$datum['operator_id']];
                }
                if(array_key_exists($datum['wxservice_ope_id'],$wxservice_ope_names_dic)) {
                    $datum['wxservice_ope_name'] = $wxservice_ope_names_dic[$datum['wxservice_ope_id']];
                }
            }
            return ['code'=>ErrorCode::SUCCESS,'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),'data'=>$result['data'],'total'=>$result['total']];
        }catch (\Exception $e) {
            ServerUtil::info('基本的表单提交客服信息列表查看/admin/wxservice/index', ['error' => $e->getMessage(), 'request' => $request], 'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }

    /**
     * 小程序用户提交问题反馈
     * @Author abell
     * @DateTime 2020-05-26
     * @param array $request
     * @return array
     */
    public function formMsg($request){
        try {
            $result = make(WxserviceDao::class)->formMsg($this->jwt,$request);
            if($result){
                return ['code'=>ErrorCode::SUCCESS,'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),'data'=>$result];
            }else{
                return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>$result];
            }
        }catch (\Exception $e){
            ServerUtil::info('小程序用户提交问题反馈/api/wxservice/form_msg',['error'=>$e->getMessage(),'request'=>$request],'ERROR');
        }
    }

    /**
     * 小程序问题反馈查询
     * @Author abell
     * @DateTime 2020-05-26
     * @param array $request
     * @return array
     */
    public function formInfo(){
        try {
            $result = make(WxserviceDao::class)->formInfo($this->jwt);
            return ['code'=>ErrorCode::SUCCESS,'msg'=>ErrorCode::getMessage(ErrorCode::SUCCESS),'data'=>$result];
        }catch (\Exception $e){
            ServerUtil::info('小程序用户问题反馈查询/api/wxservice/form_msg',['error'=>$e->getMessage()],'ERROR');
            return ['code'=>ErrorCode::ERR_SERVER,'msg'=>ErrorCode::getMessage(ErrorCode::ERR_SERVER),'data'=>''];
        }
    }

    /**
     * 问题反馈 类型列表
     * @Author abell
     * @DateTime 2020-05-26
     * @param array $request
     * @return array
     */
    public function formType(){
        try {
            $result_type = make(WxserviceTypeDao::class)->getList(['*']);
            foreach ($result_type as &$res_type){
                $res_type['pid'] = $res_type['wxservice_ope_id'];
            }
            // 运营商
            $result_ope = make(WxserviceOpeDao::class)->getList(['*'],['pid'=>0]);
            $result = array_merge($result_type,$result_ope);
            return make(StringUtil::class)->arrayToTree($result);
        }catch (\Exception $e){
            ServerUtil::info('问题反馈类型列表获取/api/wxuser/get_list',['error'=>$e->getMessage()],'ERROR');
        }
    }

    /**
     * 问题反馈 分类列表 -> 运营商和油卡
     * @Author abell
     * @DateTime 2020-05-26
     * @param array $request
     * @return array
     */
    public function formOpe(){
        try {
            // 运营商
            $result_ope = make(WxserviceOpeDao::class)->getList(['*'],[]);
            return make(StringUtil::class)->arrayToTree($result_ope);
        }catch (\Exception $e){
            ServerUtil::info('问题反馈类型列表获取/api/wxuser/get_list',['error'=>$e->getMessage()],'ERROR');
        }
    }

    //-------------------------------------

    /**
     * 添加问题反馈分类
     * @param $title
     * @param $operator
     * @return int
     */
    public function classifyAdd($title, $operator = '')
    {
        $wxserviceOpeDao = make(WxserviceOpeDao::class);

        $insertArray = ['title'=>$title];
        if($wxserviceOpeDao->findByWhere(['title'=>$title, 'is_del'=>1])){
            throw new BusinessException(ErrorCode::ERR_SERVER, '分类名称已存在');
        }
        $id = $wxserviceOpeDao->add($insertArray);
        if(empty($id)){
            throw new BusinessException(ErrorCode::ERR_SERVER, '数据库插入失败');
        }

        if(!empty($operator)){
            $operatorArray = explode(',', str_replace('，', ',', $operator));
            $insertArray = ['pid'=>$id];
            foreach ($operatorArray as $v){
                if(!empty($v)){
                    $insertArray['title'] = trim($v);
                    $wxserviceOpeDao->add($insertArray);
                }
            }
        }
        make(AdminLogDao::class)->addLog('添加问题反馈分类：'.json_encode(['title'=>$title, 'operator'=>$operator]));
        return $id;
    }

    /**
     * 获取全部问题反馈分类
     * @return array
     */
    public function classifyAll()
    {
        $data = make(WxserviceOpeDao::class)->getAll(['id', 'pid', 'title']);
        $list = [];
        if(!empty($data)){
            foreach ($data as $v){
                if($v['pid']){
                    $list[$v['pid']]['operator'] = empty($list[$v['pid']]['operator']) ? $v['title'] : $list[$v['pid']]['operator'] . ',' . $v['title'];
                }else{
                    $list[$v['id']]['id'] = $v['id'];
                    $list[$v['id']]['title'] = $v['title'];
                }
            }
        }
        $list =  array_values($list);
        return $list;
    }

    /**
     * 编辑问题反馈分类
     * @param $id
     * @param $title
     * @param string $operator
     * @return bool
     */
    public function classifyEdit($id, $title, $operator = '')
    {
        $wxserviceOpeDao = make(WxserviceOpeDao::class);

        $classify = $wxserviceOpeDao->findById($id, ['*'], true);
        if(empty($classify)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '分类不存在');
        }
        $status  = $wxserviceOpeDao->findByWhere(['title'=>$title, 'is_del'=>1]);
        if($status && $status['id'] != $id){
            throw new BusinessException(ErrorCode::ERR_SERVER, '分类名称已存在');
        }
        if($title != $classify['title']){
            $wxserviceOpeDao->updateById($id, ['title' => $title]);
        }

        $operatorList = $wxserviceOpeDao->getAllByWhere(['pid'=>$id, 'is_del' => 1]);//查询已存在的
        if(empty($operator)){
            $wxserviceOpeDao->updateByWhere(['pid'=>$id], ['is_del' => 2]);
        }else{

            $operatorArray = explode(',', str_replace('，', ',', $operator));
            $operatorTitleList = array_column($operatorList, 'title');

            $diffAddArray = array_diff($operatorArray, $operatorTitleList);//需要新增的
            $diffDelArray = array_diff($operatorTitleList, $operatorArray);//需要删除的

            $insertArray = ['pid'=>$id];
            if($diffDelArray){
                $wxserviceOpeDao->updateByWhere($insertArray, ['is_del' => 2], $diffDelArray);//删除需要删除的
            }
            foreach ($diffAddArray as $v){
                if(!empty($v)){
                    $insertArray['title'] = trim($v);
                    $insertArray['is_del'] = 2;
                    $info = $wxserviceOpeDao->findByWhere($insertArray, ['id']);
                    if(empty($info)){
                        unset($insertArray['is_del']);
                        $wxserviceOpeDao->add($insertArray);
                    }else{
                        $wxserviceOpeDao->updateById($info['id'], ['is_del'=>1]);
                    }

                }
            }
        }
        make(AdminLogDao::class)->addLog('编辑问题反馈分类：编辑前 ' . json_encode(['title'=>$classify['title'], 'operator'=>$operatorList]) . ' 编辑后 ' . json_encode(['title'=>$title, 'operator'=>$operator]));
        return true;

    }

    /**
     * 获取问题反馈分类详情
     * @param $id
     * @return array
     */
    public function classifyGet($id)
    {
        $wxserviceOpeDao = make(WxserviceOpeDao::class);

        $classify = $wxserviceOpeDao->findById($id, ['id', 'title'], true);
        if(empty($classify)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '分类不存在');
        }

        $classify['operator'] = '';
        $operatorArray = $wxserviceOpeDao->getAllByWhere(['pid'=>$id, 'is_del' => 1], ['title']);
        if(!empty($operatorArray)){
            foreach ($operatorArray as  $v){
                $classify['operator'] = empty($classify['operator']) ? $v['title'] : $classify['operator'] . ',' . $v['title'];
            }

        }

        return $classify;
    }

    /**
     * 删除问题反馈分类
     * @param $id
     * @return bool
     */
    public function classifyDel($id)
    {
        $wxserviceOpeDao = make(WxserviceOpeDao::class);
        if(make(WxserviceTypeDao::class)->findByWhere(['wxservice_ope_id'=>$id, 'is_del'=>1])){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '该分类下存在问题类型，请先删除该分类下的问题类型');
        }
        $classify = $wxserviceOpeDao->findById($id, ['id', 'title'], true);
        $wxserviceOpeDao->updateById($id, ['is_del' => 2]);
        $wxserviceOpeDao->updateByWhere(['pid'=>$id], ['is_del' => 2]);
        make(AdminLogDao::class)->addLog('删除问题反馈分类：' . json_encode($classify));
        return true;

    }

    /**
     * 添加问题类型
     * @param $insertArray
     * @return int
     */
    public function typeAdd($insertArray)
    {
        $wxserviceTypeDao = make(WxserviceTypeDao::class);

        if(!make(WxserviceOpeDao::class)->findById($insertArray['wxservice_ope_id'], ['id'], true)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '分类不存在');
        }

        $insertArray['is_del'] = 1;
        if($wxserviceTypeDao->findByWhere($insertArray)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '该问题类型已存在');
        }
        make(AdminLogDao::class)->addLog('添加问题类型：' . json_encode($insertArray));
        return $wxserviceTypeDao->add($insertArray);

    }

    /**
     * 获取全部问题类型
     * @param $insertArray
     * @return int
     */
    public function typeAll()
    {
        return make(WxserviceTypeDao::class)->getAll(['wxservice_type.id', 'wxservice_type.title', 'wxservice_ope.title as classify_title', 'wxservice_ope.id as wxservice_ope_id']);

    }


    /**
     * 编辑问题类型
     * @param $info
     * @return int
     */
    public function typeEdit($info)
    {
        $wxserviceTypeDao = make(WxserviceTypeDao::class);

        $id = $info['id'];
        unset($info['id']);
        $data = $wxserviceTypeDao->findById($id);
        if(empty($data)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '该问题类型不存在');
        }


        if(!make(WxserviceOpeDao::class)->findById($info['wxservice_ope_id'], ['id'], true)){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '分类不存在');
        }
        $status = $wxserviceTypeDao->findByWhere($info);
        if($status && $status['id'] != $id){
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '该问题类型已存在');
        }
        make(AdminLogDao::class)->addLog('编辑问题类型：编辑前 ' . json_encode($data) . '编辑后 ' . json_encode($info));
        return  $wxserviceTypeDao->updateById($id, $info);

    }


    /**
     * 获取问题类型
     * @param $id
     * @return array
     */
    public function typeGet($id)
    {
        return  make(WxserviceTypeDao::class)->findById($id, ['id', 'title', 'wxservice_ope_id']);

    }


    /**
     * 删除问题类型
     * @param $id
     * @return int
     */
    public function typeDel($id)
    {
        $data = make(WxserviceTypeDao::class)->findById($id);
        if($data){
            make(AdminLogDao::class)->addLog('删除问题类型：' . json_encode($data));
        }
        return  make(WxserviceTypeDao::class)->updateById($id, ['is_del'=>2]);

    }

    /**
     * 获取反馈数据排行列表数据
     * @param int $pageSize
     * @return array
     */
    public function countRankList($pageSize = 5)
    {
        $list = make(WxserviceDao::class)->getCountRankListPage(null, $pageSize);
        if(!empty($list['list'])){
            $titleArray = make(WxserviceOpeDao::class)->getAllByWhere([], ['id', 'title']);
            $titleArray = array_column($titleArray, 'title', 'id');
            foreach ($list['list'] as $k => $v){
                $list['list'][$k]['title'] = @$titleArray[$v['operator_id']];
            }
        }
        return $list;
    }

    /**
     * 获取反馈数据类型排行列表数据
     * @param int $pageSize
     * @return array
     */
    public function countTypeRankList($pageSize = 5)
    {
        $list = make(WxserviceDao::class)->getCountTypeRankListPage(null, $pageSize);
        /*if(!empty($list['list'])){
            $titleArray = make(WxserviceTypeDao::class)->getAllByWhere([], ['id', 'title']);
            $titleArray = array_column($titleArray, 'title', 'id');
            foreach ($list['list'] as $k => $v){
                $list['list'][$k]['title'] = @$titleArray[$v['type_id']];
            }
        }*/
        return $list;
    }

}